<?php

namespace app\common\model;

use think\Db;
use think\Model;

class Goods extends Model
{
    // 表名
    protected $name = 'goods';
    
    // 自动写入时间戳字段
    protected $autoWriteTimestamp = true;

    
    // 追加属性
    protected $append = [
        'is_virtual_text',
        'virtual_refund_text',
        'is_on_sale_text',
        'is_free_shipping_text',
        'create_time_text',
        'is_recommend_text',
        'is_new_text',
        'is_hot_text',
        'update_time_text',
	    'effective_time_text',
	    'goods_type_text'
    ];
    

    
    public function getIsVirtualList()
    {
        return ['1' => '是', '0' => '否'];
    }     

    public function getVirtualRefundList()
    {
	    return ['1' => '是', '0' => '否'];
    }     

    const IS_ON_SALE_Y = 1;
	const IS_ON_SALE_N = 0;
	const IS_ON_SALE_W = 2;
    
    public function getIsOnSaleList()
    {
        return [self::IS_ON_SALE_Y => '上架', self::IS_ON_SALE_N => '下架', self::IS_ON_SALE_W => '审核中'];
    }     

    public function getIsFreeShippingList()
    {
	    return ['1' => '是', '0' => '否'];
    }     

    const RECOMMEND_Y = 1;
	const RECOMMEND_N = 0;
    public function getIsRecommendList()
    {
	    return [self::RECOMMEND_Y => '是', self::RECOMMEND_N => '否'];
    }     

    const IS_NEW_Y = 1;
    const IS_NEW_N = 0;
    public function getIsNewList()
    {
	    return [self::IS_NEW_Y => '是', self::IS_NEW_N => '否'];
    }     

    const HOT_Y = 1;
    const HOT_N = 0;
    public function getIsHotList()
    {
	    return [self::HOT_Y => '是', self::HOT_N => '否'];
    }     

    
    const GOODS_TYPE_1 = 1;
	const GOODS_TYPE_2 = 2;
	const GOODS_TYPE_3 = 3;
	
	
	public static $goodsTypeList = [
		self::GOODS_TYPE_1 => '普通商品',
		self::GOODS_TYPE_2 => '分期商品',
		self::GOODS_TYPE_3 => '押金商品'
	];
	
	public function getGoodsTypeTextAttr($value, $data) {
		$value = $value ? : $data['goods_type'];
		$list = self::$goodsTypeList;
		return isset($list[$value]) ? $list[$value] : '';
	}
	
	
	const REBATE_GLOBAL = 1;
	const REBATE_ONE = 2;
	
	public static $rebateTypeList = [
		self::REBATE_GLOBAL => '全局配置',
		self::REBATE_ONE => '单独配置'
	];

    public function getIsVirtualTextAttr($value, $data)
    {        
        $value = $value ? $value : $data['is_virtual'];
        $list = $this->getIsVirtualList();
        return isset($list[$value]) ? $list[$value] : '';
    }


    public function getVirtualRefundTextAttr($value, $data)
    {        
        $value = $value ? $value : $data['virtual_refund'];
        $list = $this->getVirtualRefundList();
        return isset($list[$value]) ? $list[$value] : '';
    }


    public function getIsOnSaleTextAttr($value, $data)
    {        
        $value = $value ? $value : $data['is_on_sale'];
        $list = $this->getIsOnSaleList();
        return isset($list[$value]) ? $list[$value] : '';
    }


    public function getIsFreeShippingTextAttr($value, $data)
    {        
        $value = $value ? $value : $data['is_free_shipping'];
        $list = $this->getIsFreeShippingList();
        return isset($list[$value]) ? $list[$value] : '';
    }


    public function getCreateTimeTextAttr($value, $data)
    {
        $value = $value ? $value : $data['create_time'];
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }
	
	public function getEffectiveTimeTextAttr($value, $data)
	{
		$value = $value ? $value : $data['effective_time'];
		return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
	}

    public function getIsRecommendTextAttr($value, $data)
    {        
        $value = $value ? $value : $data['is_recommend'];
        $list = $this->getIsRecommendList();
        return isset($list[$value]) ? $list[$value] : '';
    }


    public function getIsNewTextAttr($value, $data)
    {        
        $value = $value ? $value : $data['is_new'];
        $list = $this->getIsNewList();
        return isset($list[$value]) ? $list[$value] : '';
    }


    public function getIsHotTextAttr($value, $data)
    {        
        $value = $value ? $value : $data['is_hot'];
        $list = $this->getIsHotList();
        return isset($list[$value]) ? $list[$value] : '';
    }


    public function getUpdateTimeTextAttr($value, $data)
    {
        $value = $value ? $value : $data['update_time'];
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }

    protected function setCreateTimeAttr($value)
    {
        return $value && !is_numeric($value) ? strtotime($value) : $value;
    }

    protected function setUpdateTimeAttr($value)
    {
        return $value && !is_numeric($value) ? strtotime($value) : $value;
    }
    
	protected function setEffectiveTimeAttr($value)
	{
		return $value && !is_numeric($value) ? strtotime($value) : $value;
	}
	
	public function category(){
		return $this->belongsTo('goodsCategory', 'category_id', 'id','', 'left')->setEagerlyType(0);
	}
	
	public function brand(){
		return $this->belongsTo('brand', 'brand_id', 'id','', 'left')->setEagerlyType(0);
	}
	
	public function business(){
		return $this->belongsTo('business', 'business_id', 'id','', 'left')->setEagerlyType(0);
	}
	
	/**
	 * 添加商品相册
	 * @param $goodsId
	 * @param $list
	 * @param $type
	 * @return bool
	 */
	public function addImglist($goodsId, $list, $type){
        $imgs = explode(',',$list);
        
        //添加商品时
        if($type == 1){
        	$data = [];
            foreach($imgs as $img){
                $data[] = [
                    'goods_id' => $goodsId,
	                'image_url' => $img,
                ];
            }
            
            $res = Db::name('GoodsImages')->insertAll($data);
            if($res === false){
            	return false;
            }
        } else {
        	$rows = Db::name('GoodsImages')->where(['goods_id' => $goodsId])->column('image_url', 'id');
        	
        	//要删除的图片
        	$delIds = [];
        	foreach ($rows as $key => $url){
        		if(!in_array($url, $imgs)){
        			$delIds[] = $key;
		        }
	        }
	        
	        if($delIds){
        		$delRes = Db::name('GoodsImages')->where(['id' => ['in', $delIds]])->delete();
        		if(!$delRes){
        			$this->error = '删除图片出错';
        			return false;
		        }
	        }
	        
	        
	        //要添加的图片
	        $data = [];
	        foreach($imgs as $img){
	        	if(!in_array($img, $rows)){
			        $data[] = [
				        'goods_id' => $goodsId,
				        'image_url' => $img,
			        ];
		        }
	        }
			if($data){
				$res = Db::name('GoodsImages')->insertAll($data);
				if($res === false){
					return false;
				}
			}
        }
        
        return true;
	}
	
	/**
	 * 添加规格
	 * @param $goodsId 商品ID
	 * @param $spec 规格
	 * @param int $type 1添加2编辑
	 * @return bool
	 */
	public function addSpec($goodsId, $spec, $type = 1){
		if($type == 1){
			$datas = [];
			foreach($spec as $key => $item){
				$datas[] = [
					'goods_id' => $goodsId,
					'key' => $key,
					'spec_name' => $item['spec_name'],
					'price' => $item['price'],
					'store_count' => $item['store_count'],
					'sku' => $item['sku'],
				];
			}
			
			$addRes = Db::name('goodsSpecPrice')->insertAll($datas);
			if(!$addRes){
				$this->error = '添加商品规格出错';
				return false;
			}
		} else {
			$keys = array_keys($spec);
			$items = Db::name('goodsSpecPrice')->where(['goods_id' => $goodsId])->select();
			$delIds = [];
			$editKeys = [];
			if($items) {
				foreach ($items as $item) {
					if(!in_array($item['key'], $keys)) {
						$delIds[] = $item['id'];
					} else {
						$editKeys[] = $item['key'];
					}
				}
			}
			
			$datas = [];
			foreach($spec as $key => $item){
				if(in_array($key, $editKeys)) {
					$data = [
						'goods_id' => $goodsId,
						'key' => $key,
						'spec_name' => $item['spec_name'],
						'price' => $item['price'],
						'store_count' => $item['store_count'],
						'sku' => $item['sku'],
					];
					$editRes = Db::name('goodsSpecPrice')->where(['goods_id' => $goodsId, 'key' => $key])->update($data);
					if($editRes === false) {
						$this->error = '更改商品规格价格出错';
						return false;
					}
				} else {
					$datas[] = [
						'goods_id' => $goodsId,
						'key' => $key,
						'spec_name' => $item['spec_name'],
						'price' => $item['price'],
						'store_count' => $item['store_count'],
						'sku' => $item['sku'],
					];
				}
				
			}
			
			if($datas) {
				$addRes = Db::name('goodsSpecPrice')->insertAll($datas);
				if(!$addRes){
					$this->error = '添加商品规格出错';
					return false;
				}
			}
			
			if($delIds) {
				$delRes = Db::name('goodsSpecPrice')->where(['id' => ['in', $delIds]])->delete();
				if(!$delRes) {
					$this->error = '删除商品原规格出错';
					return false;
				}
			}
			
		}
		return true;
	}
	
	
	public function addAttr($goodsId, $attr, $type = 1){
		$model = Db::name('goodsAttrValue');
		
		$attr = array_filter($attr);
		$arr = [];
		if($attr){
			foreach ($attr as $key => $value){
				if(is_array($value)){
					$value = array_filter($value);
					if(!$value){
						continue;
					} else {
						$value = implode(' ',$value);
					}
				}
				
				$arr[$key] = $value;
			}
		}
		
		$attr = $arr;
		
		
		if($type == 1 && $attr){
			$datas = [];
			foreach ($attr as $key => $value){
				if($value){
					if(is_array($value)){
						$value = array_filter($value);
						$value = implode(' ', $value);
					}
					
					$datas[] = [
						'goods_id' => $goodsId,
						'attr_id' => $key,
						'value' => $value,
					];
				}
			}
			
			if($datas){
				$addRes = $model->insertAll($datas);
				if(!$addRes){
					$this->error('添加属性值出错');
					return false;
				}
			}
		} else {
			$rows = $model->where(['goods_id' => $goodsId])->select();
			$ids = array_keys($attr);
			$delIds = [];
			$attrIds = [];
			if($rows){
				foreach ($rows as $row){
					if(!in_array($row['attr_id'], $ids)){
						$delIds[] = $row['id'];
					} elseif($row['value'] != $attr[$row['attr_id']]){
						$value = $attr[$row['attr_id']];
						$updateRes = $model->where(['id' => $row['id']])->update(['value' => $value]);
						if(!$updateRes){
							$this->error = '更改属性值出错'.$model->getLastSql();
							return false;
						}
					}
					
					$attrIds[] = $row['attr_id'];
					
				}
				
			}
				if($delIds){
					$delRes = $model->where(['id' => ['in', $delIds]])->delete();
					if(!$delRes){
						$this->error = '删除属性出错';
						return false;
					}
				}
				$datas = [];
				foreach ($attr as $k => $v){
					if(!in_array($k, $attrIds)){
						$datas[] = [
							'goods_id' => $goodsId,
							'attr_id' => $k,
							'value' => $v,
						];
					}
				}
				
				if($datas){
					$addRes = $model->insertAll($datas);
					if(!$addRes){
						$this->error('添加属性值出错');
						return false;
					}
				}
			
		}
		return true;
	}
	
	
	/**
	 * 统计商品状态数量
	 * @param $busId string 商家ID
	 * @return array
	 */
	public function countList($busId='') {
		$countWhere = [];
		
		$busId && $countWhere['business_id'] = $busId;
		
		$count = Db::name('goods')
			->where($countWhere)
			->group('is_on_sale')
			->column('count(id) as number', 'is_on_sale');
		
		$status = $this->getIsOnSaleList();
		$countList = [];
		$class = [
			self::IS_ON_SALE_Y => 'btn-success',
			self::IS_ON_SALE_N => 'btn-warning',
			self::IS_ON_SALE_W => 'btn-primary',
		];
		foreach($status as $k => $v){
			$countList[] = [
				'name' => $v,
				'number' => isset($count[$k]) ? $count[$k] : 0,
				'value' => $k,
				'class' => $class[$k]
			];
		}
		
		return $countList;
	}
	
	/**
	 * 获取商品标签
	 * @param $goodsType
	 * @param $grade
	 * @return array
	 */
	public function getGoodsTags($goodsType, $grade){
		$tags = [];
		if($goodsType == self::GOODS_TYPE_2) {
			$tags[] = [
				'color' => '#e60012',
				'name' => self::$goodsTypeList[$goodsType],
			];
		}
		
		
		if($goodsType == self::GOODS_TYPE_3) {
			$tags[] = [
				'color' => '#007aff',
				'name' => self::$goodsTypeList[$goodsType],
			];
		}
		
		if($grade == \app\admin\model\User::LEVEL_1) {
			$tags[] = [
				'color' => '#4cd964',
				'name' => '会员商品',
			];
		} else if($grade > 0) {
			$tags[] = [
				'color' => '#8a6de9',
				'name' => '代理商品',
			];
		}
		
		return $tags;
	}
}
